package leetcode.code1477;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int minSumOfLengths(int[] arr, int target) {
		int sum = 0, l = 0, r = -1;
		int len = arr.length;
		int[] start = new int[len];
		int[] end = new int[len];
		while (r < len && l < len) {
			while (r < len - 1 && sum < target) {
				sum += arr[++r];
			}
			if (sum == target) {
				int size = r - l + 1;
				start[l] = size;
				end[r] = size;
			}
			sum -= arr[l++];
		}
		int starts[] = new int[len];
		int ends[] = new int[len];
		int mine = Integer.MAX_VALUE;
		int mins = Integer.MAX_VALUE;
		for (int i = 0, j = len - 1; i < len; i++, j--) {
			if (mins != Integer.MAX_VALUE) {
				starts[j] = mins;
			}
			int e = end[i];
			int s = start[j];
			if (e != 0) {
				mine = Math.min(mine, e);
			}
			if (s != 0) {
				mins = Math.min(mins, s);
			}
			if (mine != Integer.MAX_VALUE) {
				ends[i] = mine;
			}
		}
		int ans = Integer.MAX_VALUE, cur = 0;
		for (int i = 0; i < len; i++) {
			if (ends[i] != 0 && starts[i] != 0 && (cur = ends[i] + starts[i]) < ans) {
				ans = cur;
			}
		}
		return ans == Integer.MAX_VALUE ? -1 : ans;
	}

	@Override
	public void debug4() {
		H.compare(-1, this.minSumOfLengths(H.str2array3("[4,3,2,6,2,3,4]"), 6));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
